package org.wattdepot.gdata.kukuicup.updater.powerlastfewminutes;

import java.util.Timer;
import java.util.TimerTask;
import org.wattdepot.gdata.kukuicup.service.GDataService;
import org.wattdepot.gdata.kukuicup.service.WattDepotService;
import org.wattdepot.gdata.kukuicup.updater.Updater;

/**
 * Implements the PowerLastFewMinutes Updater, which creates individual timer tasks for
 * each source that run once every 15 seconds and update the spreadsheet with the most
 * recent values.  
 * @author Philip Johnson
 */
public class PowerLastFewMinutesUpdater extends Updater {
  
  /**
   * Creates this updater, initializing the various services. 
   * @param wattDepotService The wattdepot service. 
   * @param gdataService The gdata service.
   * @throws Exception If problems occur initializing these services.  
   */
  public PowerLastFewMinutesUpdater(WattDepotService wattDepotService, GDataService gdataService) 
  throws Exception {
    super("PowerLastFewMinutes", wattDepotService, gdataService);
  }


  /**
   * This task generates a separate TimerTask for each source in the spreadsheet. 
   * Each TimerTask runs every 15 seconds, gets the most recent power sensor data for
   * its source, then writes out the last 10 data points to the spreadsheet.
   */
  @Override
  public void run() {
    int delay = 0;
    for (String sourceName : sourceNames) {
      Timer timer = new Timer();
      TimerTask task = new PowerLastFewMinutesTask(wattDepotService, gdataService, 
          spreadsheetURL, sourceName, isVirtual(sourceName), getRow(sourceName));
      int fifteenSecondUpdates = 1000 * 15;
      timer.schedule(task, delay, fifteenSecondUpdates);
      // space out these tasks by 10 seconds so they don't hit the WattDepot all at once.  
      delay += 1000 * 10;
      timers.add(timer);
    }
  }


}
